import { getUsersApi } from '@/api/usersApi'
import type { UsersListType } from '@/typings/usersType'
import { useRouter, useRoute } from 'vue-router'
import {ref,onMounted,computed} from 'vue'
import type {Ref} from 'vue'
import { objToQuery } from '@/utils/tools'

export const useUserList = (pageNum = 1):[Ref<UsersListType[]>,Ref<number>,(page:number) => Promise<void>,Ref<number>] => {
    const router = useRouter()
    const route = useRoute()

    const data = ref<UsersListType[]>([])
    const total = ref(0)

    const currentPage = computed(() => {
        return route.query.page ? +route.query.page : 1
    })

    const loadData = async(page: number , search?: Record<string, string> | undefined)=>{
        let query = ''
        if(typeof search != 'undefined') {
            query = objToQuery(search)
        }

        router.replace(`?page=${page}${query}`)
        let ret = await getUsersApi(currentPage.value,query)
        if(ret.code === 0){
            data.value = ret.data.users
            total.value = ret.data.total
        }
    }

    onMounted(() => {
        loadData(currentPage.value)
    })

    return [data,total,loadData,currentPage]

}